import json
import pickle
import time
import datetime
import random
from weibosender.weibo.weibo import Weibo
from weibosender.dal.senders_dal import SendersDAL


class WeiboLoginHandler:
    @staticmethod
    def login(users):
        for user in users:
            sender_id = user[0]
            uid = user[3]
            cookies_bytes = user[4]
            if uid and cookies_bytes:
                try:
                    pickle.loads(cookies_bytes)
                    continue
                except Exception as e:
                    print('解析记录中的cookies失败\nException：%s' % e)
            result = WeiboLoginHandler._handle(user)
            if not result:
                continue
            WeiboLoginHandler._update(sender_id, result)
            time.sleep(random.randint(5, 10))

        return SendersDAL.get_logged() > 0

    @staticmethod
    def _handle(user):
        login_name = user[1]
        login_result = Weibo.login([login_name, user[2]])
        if not login_result:
            return None

        response_text = login_result['response_text']
        cookies = login_result['cookies']

        if not response_text:
            print('登录失败 > 用户名：%s\nResponseText：%s' % (login_name, response_text))
            return None
        try:
            json_obj = json.loads(response_text)
        except Exception as e:
            print('登录失败 > 用户名：%s\nException：%s' % (login_name, e))
            return None
        code = json_obj['retcode']

        if code != 20000000:
            print('登录失败 > code:%s，用户名：%s，msg:%s' % (code, login_name, json_obj['msg']))
            return None

        print('登录成功 > %s' % login_name)
        uid = json_obj['data']['uid']

        return {
            'uid': uid,
            'cookies': cookies
        }

    @staticmethod
    def _update(id, user):
        if not user:
            return False
        uid = user['uid']
        cookies = pickle.dumps(user['cookies'])
        SendersDAL.update((uid, cookies, datetime.datetime.now(), id))
        return True
